<template>
	<view>
		<view class="top_bg"></view>
		<view class="top">
			<view class="top_button">
				<view class="return" @click="returnPage">
					<image :src="imageBaseUrl + '/img/return.png'"></image>
				</view>
				<view class="line"></view>
				<view class="homepage" @click="goHome">
					<image :src="imageBaseUrl + '/img/home.png'"></image>
				</view>
			</view>
			<view>订单</view>
		</view>
		<div class="header">
			<div style="height: 222px;"></div>
			<div class="date">
				2025-03-11——2025-04-21
			</div>
			<div class="prizes">
				<div class="prize" v-for="(item, index) in prizeList" :key="index"
					:style="{ backgroundColor: index === currentActive ? activeColor : defaultColor }">
					<div class="prize_img">
						<image :src="item.img" mode="aspectFill" v-if="item.name != '谢谢惠顾'"></image>
						<image :src="imageBaseUrl + '/img/handshake.png'" mode="aspectFill" v-if="item.name == '谢谢惠顾'">
						</image>
					</div>
					<div class="prize_text">
						{{ item.name }}
					</div>
				</div>
			</div>
			<div class="bottom">
				<!-- 新增disabled属性绑定 -->
				<div class="end" @click="requestStopAnimation" :disabled="isEndDisabled"></div>
				<div class="begin" @click="startAnimation" :disabled="isStartDisabled"></div>
			</div>
			<div class="more">
				<div @click="openModal()">查看攻略</div>
				<div class="more_text" @click="more">
					<div>更多</div>
					<div class="more_img">
						<image :src="imageBaseUrl + '/img/right.png'"></image>
					</div>
				</div>

			</div>
			<div class="tables">
				<div class="table_item">
					<div class="table_item_text" style="width: 10%;">序号</div>
					<div class="table_item_text" style="width: 25%;">昵称</div>
					<div class="table_item_text" style="width: 30%;">奖品</div>
					<div class="table_item_text" style="width: 35%;">时间</div>
				</div>
				<div class="table_items">
					<div v-for="(item, index) in records" :key="index" style="display: flex;">
						<div class="table_item_text" style="width: 10%;">{{ index + 1 }}</div>
						<div class="table_item_text" style="width: 25%;">{{ item.nickname }}</div>
						<div class="table_item_text" style="width: 30%;">{{ item.name }}</div>
						<div class="table_item_text" style="width: 35%;">{{ item.create_time }}</div>
					</div>

				</div>
			</div>
			<uv-modal ref="modalRef" title="活动流程" content="523" showCancelButton="true"
				@confirm="confirm" confirmText="我已阅读" confirmColor="#FCD570" />
		</div>
	</view>
</template>

<script setup>
import { ref, onUnmounted, onMounted } from 'vue';
import api from '../../api/activity/index.js';
import config from '../../config/index.js';
const imageBaseUrl = config.image;

// 新增按钮禁用状态
const isStartDisabled = ref(false); // 开始按钮禁用状态
const isEndDisabled = ref(true); // 结束按钮禁用状态
// 创建对模态框组件的引用
const modalRef = ref(null);
// 抽奖奖品配置（可自定义概率，总和建议100%）
const prizeList = ref([
	{ name: '一等奖', probability: 5 },
	{ name: '二等奖', probability: 10 },
	{ name: '三等奖', probability: 15 },
	{ name: '谢谢参与', probability: 20 },
	{ name: '幸运奖', probability: 15 },
	{ name: '优惠券', probability: 20 },
	{ name: '纪念奖', probability: 10 },
	{ name: '谢谢参与', probability: 5 },
]);
//中奖记录
const records = ref([]);
// 状态变量
const currentActive = ref(-1); // 当前激活格子索引
const timer = ref(null); // 定时器
const isRunning = ref(false); // 动画运行状态
const isStopping = ref(false); // 是否正在执行结束动画
const defaultColor = ''; // 原始背景色
const isActive = ref('2');// 是否中奖
const isShow = ref('3');// 是否显示
const activeColor = 'rgba(110, 45, 45, 0.416)'; // 高亮颜色
const stopSpinCount = ref(0); // 点击结束后已旋转的圈数
const targetSpinCount = 3; // 目标额外旋转圈数
const data = ref([]);//  活动数据

// 动画参数配置（优化后参数）
const configs = {
	initialInterval: 600, // 初始间隔时间（毫秒）
	minInterval: 50, // 最小间隔时间（加速终点，也是匀速阶段间隔）
	accelerationFactor: 2.2, // 加速因子（提高加速速度）
	decelerationFactor: 1.5, // 减速因子（大于1才能减速，值越大减速越明显）
	accelerationDuration: 3000, // 加速持续时间（毫秒）
	constantDuration: 2000, // 匀速持续时间（毫秒）
	slowDownThreshold: 300, // 开始减速的阈值（毫秒）
	spinCount: 2, // 基础旋转圈数（至少旋转圈数）
};

// 新增状态：当前动画阶段
const animationPhase = ref('idle'); // idle/accelerating/constant/decelerating

// 计算中奖索引（轮盘赌算法）
const calculateWinIndex = () => {
	const totalProbability = prizeList.value.reduce((sum, item) => sum + item.probability, 0);
	const random = Math.random() * totalProbability;
	let cumulative = 0;

	for (let i = 0; i < prizeList.value.length; i++) {
		cumulative += prizeList.value[i].probability;
		if (random < cumulative) return i;
	}
	return 0; // 保底返回第一个（概率总和应为100%，此情况理论不会出现）
};
//点击更多
const more = () => {
	uni.navigateTo({
		url: "/pages/record/record",
	});
}
// 打开模态框的方法
const openModal = (ids) => {
	modalRef.value?.open();
};
//  确认按钮点击事件
const confirm = () => {
	console.log('点击确认按钮');
};
// 动画主函数（核心逻辑修正：仅用户点击结束时减速）
const animate = (startTime, interval, spinCount, lastIndex) => {
	if (!isRunning.value) return;

	const elapsedTime = Date.now() - startTime;
	let nextIndex = (currentActive.value + 1) % 8;
	currentActive.value = nextIndex;

	// 精准计算完整圈数（0→7→0为一圈）
	const isNewCircle = (lastIndex === 7 && nextIndex === 0);
	const newSpinCount = spinCount + (isNewCircle ? 1 : 0);

	let newInterval = interval;
	let newPhase = animationPhase.value;

	// ------------------- 加速阶段 -------------------
	if (newPhase === 'accelerating' || newPhase === 'idle') {
		// 计算加速阶段间隔时间（不低于最小间隔）
		newInterval = Math.max(
			configs.minInterval, // 最低速度限制
			configs.initialInterval / Math.pow(configs.accelerationFactor, elapsedTime / 1000)
		);

		// 加速完成后进入匀速阶段（移除自动减速触发）
		if (newInterval <= configs.minInterval) {
			newPhase = 'constant'; // 加速完成，进入匀速
			newInterval = configs.minInterval; // 锁定匀速间隔
		}
	}

	// ------------------- 匀速阶段 -------------------
	if (newPhase === 'constant') {
		newInterval = configs.minInterval; // 保持最小间隔匀速运行
	}

	// ------------------- 减速阶段（仅用户点击结束时触发） -------------------
	if (isStopping.value) {
		// 首次减速时从略高于最小值开始
		if (newInterval === configs.minInterval) {
			newInterval = configs.minInterval * 1.2; // 初始减速间隔
		}
		// 应用减速因子并限制最大间隔
		newInterval = Math.min(newInterval * configs.decelerationFactor, 1000); // 最大间隔1秒
		console.log(`减速中，当前间隔：${newInterval}ms`);

		// 停止条件：达到总圈数（基础圈数+额外圈数）且间隔足够大
		if (newSpinCount >= configs.spinCount + targetSpinCount && newInterval >= 500) {
			stopAnimation();
			return;
		}
	}

	// 更新阶段状态（仅减速时标记为decelerating，否则保持accelerating/constant）
	animationPhase.value = isStopping.value ? 'decelerating' : newPhase;
	console.log('当前阶段:', animationPhase.value, '间隔:', newInterval, '当前圈数:', newSpinCount);

	// 更新按钮禁用状态
	isStartDisabled.value = isRunning.value; // 动画运行中禁用开始按钮
	isEndDisabled.value = animationPhase.value === 'accelerating'; // 加速阶段禁用结束按钮

	// 递归调用
	timer.value = setTimeout(() => {
		animate(startTime, newInterval, newSpinCount, nextIndex);
	}, newInterval);
};

// 开始动画（重置阶段状态）
const startAnimation = () => {
	if (isStartDisabled.value) return; // 禁用状态下不响应

	isStartDisabled.value = true; // 点击开始后立即禁用
	isRunning.value = true;
	isStopping.value = false;
	stopSpinCount.value = 0;
	currentActive.value = -1; // 初始位置重置
	animationPhase.value = 'accelerating'; // 初始阶段为加速

	const startTime = Date.now();
	let interval = configs.initialInterval;

	if (timer.value) clearTimeout(timer.value);
	animate(startTime, interval, 0, -1); // 初始lastIndex设为-1（避免首帧误判圈数）
};

// 请求结束动画（点击结束按钮时调用）
const requestStopAnimation = () => {
	if (!isRunning.value || isEndDisabled.value || isStopping.value) return; // 禁用状态下不响应
	isStopping.value = true;
	stopSpinCount.value = 0;
	console.log('开始减速停止动画');
};

// 实际停止动画（达到目标圈数后调用）
const stopAnimation = () => {
	isRunning.value = false;
	isStopping.value = false;

	if (timer.value) {
		clearTimeout(timer.value);
	}

	// 核心抽奖逻辑：计算目标中奖位置
	const targetIndex = calculateWinIndex();
	currentActive.value = targetIndex; // 直接定位到中奖格子
	console.log(`抽奖结果：第${targetIndex}格，奖品：${prizeList.value[targetIndex].name}`);
	if (prizeList.value[targetIndex].name === '谢谢惠顾') {
		uni.showToast({
			title: '很遗憾，您没有中奖',
			icon: 'none'
		});
	} else {
		uni.showToast({
			title: '恭喜，您中奖了',
			icon: 'success'
		});
		api.award({
			user_id: uni.getStorageSync('token').id,
			scenic_id: isShow.value,
			active_id: isActive.value,
			name: prizeList.value[targetIndex].name,
			status: 1,
			img: prizeList.value[targetIndex].img,
		}, {
			id: uni.getStorageSync('token').id,
		}
		).then(res => {
			console.log(res)
			if (res.code == 1) {
				api.activity({
					user_id: uni.getStorageSync('token').id,
				}).then((res) => {
					console.log(res.data);
					records.value = res.data;
				});
			}
		});
	}

	// 恢复按钮状态
	isStartDisabled.value = false; // 解除开始按钮禁用
	isEndDisabled.value = true; // 结束后默认禁用结束按钮（可根据需求调整）
};

// 导航功能
const returnPage = () => uni.navigateBack({ delta: 1 });
const goHome = () => uni.navigateTo({ url: '/pages/home/home' });

// 组件卸载时清除定时器
onUnmounted(() => {
	if (timer.value) clearTimeout(timer.value);
});
onMounted(() => {
	api.activitys({
		active_id: isActive.value,
	}).then((res) => {
		const activityList = res.data.slice(0, 8);
		console.log('活动列表数据：', activityList);

		// 使用索引位置映射概率
		prizeList.value = activityList.map((item, index) => {
			const originalProbability = index < 8 ? prizeList.value[index]?.probability || 0 : 0;
			return {
				name: item.name,
				probability: originalProbability,
				img: imageBaseUrl + '/img/gifts.png',
				id: item.id
			};
		});

		console.log('prizeList:', prizeList.value);
	});
	api.activity({
		user_id: uni.getStorageSync('token').id,
	}).then((res) => {
		console.log(res.data);
		records.value = res.data;
	});
	api.notice({
		scenic_id:3,
	}).then((res) => {
		console.log(res.data);
	})
});
</script>

<style scoped>
.tables {
	width: 88%;
	margin-left: 6%;
	margin-top: 40px;
	height: 270px;
	font-size: 14px;
	color: #424242;
}

.more {
	display: flex;
	justify-content: space-between;
	width: 90%;
	margin-left: 5%;
	margin-top: 27px;
}

.more_text {
	display: flex;
}

.more_img image {
	width: 15px;
	height: 15px;
}

.table_item_text {
	text-align: center;
	line-height: 40px;
}

.table_item {
	display: flex;
	width: 100%;
	height: 40px;

}

.table_items {
	width: 100%;
	height: 220px;
	overflow-y: auto;
}

.end {
	width: 40%;
	height: 30px;
	/* 新增禁用样式（可选） */
	opacity: 0.5;
	cursor: not-allowed;
}

.begin {
	width: 40%;
	height: 30px;
	/* 新增禁用样式（可选） */
	opacity: 0.5;
	cursor: not-allowed;
}

.bottom {
	width: 30%;
	height: 30px;
	margin-left: 35%;
	margin-top: -5px;
	display: flex;
	justify-content: space-between;
}

.prize_text {
	font-size: 14px;
	margin-top: 10px;
	text-align: center;
}

.prizes {
	position: relative;
	width: 76%;
	margin-left: 13%;
	margin-top: 35px;
	height: 300px;
}

.prize {
	position: absolute;
	width: 33%;
	height: 33%;
	box-sizing: border-box;
	border-radius: 5px;
	transition: background-color 0.2s ease;
	/* 添加背景色过渡动画 */
}

/* 原定位样式完全保留 */
.prize:nth-child(1) {
	top: 0;
	left: 0;
}

.prize:nth-child(2) {
	top: 0;
	left: 33.333%;
}

.prize:nth-child(3) {
	top: 0;
	left: 66.666%;
}

.prize:nth-child(4) {
	top: 32.333%;
	left: 66.666%;
}

.prize:nth-child(5) {
	top: 65.666%;
	left: 66.666%;
}

.prize:nth-child(6) {
	top: 65.666%;
	left: 33.333%;
}

.prize:nth-child(7) {
	top: 65.666%;
	left: 0;
}

.prize:nth-child(8) {
	top: 32.333%;
	left: 0;
}

.prize_img {
	width: 100%;
	height: 60%;
	display: flex;
	justify-content: center;
	align-items: center;
}

.prize_img image {
	width: 40px;
	height: 40px;
	margin-top: 20px;
}

.date {
	width: 100%;
	text-align: center;
	color: #AB0602;
	font-size: 13px;
}

.header {
	width: 100%;
	height: 1000px;
	background-image: url(http://lxj.skych.top//img/activitys.png);
	background-size: 100% 100%;
}

.line {
	width: 1%;
	background-color: #8a8a8a;
	height: 70%;
	margin-top: 5%;
}

.return {
	width: 49.5%;
	height: 100%;
	text-align: center;
	line-height: 25px;
}

.return image {
	width: 20px;
	margin-top: 2px;
	height: 20px;
}

.homepage {
	width: 49.5%;
	height: 100%;
	text-align: center;
	line-height: 25px;
}

.homepage image {
	width: 18px;
	margin-top: 3px;
	height: 18px;
}

.top_button {
	width: 70px;
	height: 25px;
	display: flex;
	border-radius: 15px;
	margin-left: 20px;
	margin-right: 23%;
	border: 1px solid rgb(192, 192, 192);
}

.header {
	width: 100%;
	position: sticky;
	top: 80px;
	margin-top: 30px;
}

.top {
	width: 100%;
	height: 50px;
	border-bottom: 1px solid rgb(203, 203, 203);
	background-color: rgba(255, 255, 255, 0.616);
	position: fixed;
	top: 30px;
	color: #8a8a8a;
	display: flex;
	align-items: center;
	z-index: 999;
}

.top_bg {
	background-color: rgb(255, 255, 255);
	width: 100%;
	height: 31px;
	position: fixed;
	top: 0;
	z-index: 999;
}
</style>